package management;

import pojo.entity.Admin;
import pojo.entity.User;
import utils.AdminConnection;
import utils.DbUtil;
import utils.UserConnection;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Scanner;

import static dao.AdminDao.*;
import static dao.UserDao.*;
import static dao.UserDao.updateUser;
import static vmmsClient.UserClient.sendLogToService;
import static management.UserManagement.*;
import static management.AdminManagement.*;


/**
 * @Author: 周训发
 * @CreateTime: 2025-11-21
 * @Description: 相同模块代码管理
 * @Version: 1.0
 */

public class CommonManagement {
    public static final int USERLOGINCOUNT = 3;   //用户登录失败次数
    /*=====================================首页=========================================*/
    public static void home(){
        System.out.println(" ");
        System.out.println("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓");
        System.out.println("┃   _       _   ____             ____   _                             __     __  __  __   __  __   ____    ┃");
        System.out.println("┃  | |     (_) | __ )    ___    / ___| | |__     ___   _ __     __ _  \\ \\   / / |  \\/  | |  \\/  | / ___|   ┃");
        System.out.println("┃  | |     | | |  _ \\   / _ \\  | |     | '_ \\   / _ \\ | '_ \\   / _` |  \\ \\ / /  | |\\/| | | |\\/| | \\___ \\   ┃");
        System.out.println("┃  | |___  | | | |_) | | (_) | | |___  | | | | |  __/ | | | | | (_| |   \\ V /   | |  | | | |  | |  ___) |  ┃");
        System.out.println("┃  |_____| |_| |____/   \\___/   \\____| |_| |_|  \\___| |_| |_|  \\__, |    \\_/    |_|  |_| |_|  |_| |____/   ┃");
        System.out.println("┃                                                              |___/                                       ┃");
        System.out.println("┃                                  林博成自动售卖机管理系统 首页！                                               ┃");
        System.out.println("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛");
        System.out.println(" ");
    }

    /*======================================用户登录模块===========================================*/
    public static void welcomePage() throws SQLException {
        System.out.println(" ");
        System.out.println("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓");
        System.out.println("┃   _       _   ____             ____   _                             __     __  __  __   __  __   ____    ┃");
        System.out.println("┃  | |     (_) | __ )    ___    / ___| | |__     ___   _ __     __ _  \\ \\   / / |  \\/  | |  \\/  | / ___|   ┃");
        System.out.println("┃  | |     | | |  _ \\   / _ \\  | |     | '_ \\   / _ \\ | '_ \\   / _` |  \\ \\ / /  | |\\/| | | |\\/| | \\___ \\   ┃");
        System.out.println("┃  | |___  | | | |_) | | (_) | | |___  | | | | |  __/ | | | | | (_| |   \\ V /   | |  | | | |  | |  ___) |  ┃");
        System.out.println("┃  |_____| |_| |____/   \\___/   \\____| |_| |_|  \\___| |_| |_|  \\__, |    \\_/    |_|  |_| |_|  |_| |____/   ┃");
        System.out.println("┃                                                              |___/                                       ┃");
        System.out.println("┃                                  林博成自动售卖机管理系统 欢迎您！                                              ┃");
        System.out.println("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛");
        System.out.println(" ");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.用户登录 2.管理员登录");
        boolean flag = true;
        while (flag) {
            String ops = scanner.next();
            switch (ops){
                case "1":{
                    userOrAdminLogin(0);
                    flag = false;
                    break;
                }
                case "2":{
                    userOrAdminLogin(1);
                    flag = false;
                    break;
                }
                default:{
                    System.out.println("操作错误,请重新输入!");
                    break;
                }
            }
        }
    }

    //用户登录
    public static void userOrAdminLogin(int isManager) throws SQLException {
        if (isManager==0){
            System.out.println("================================== 用户登录页面 ======================================");
        }else {
            System.out.println("================================== 管理员登录页面 ======================================");
        }
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        boolean isUserLogin = false;
        boolean isAdminLogin = false;
        int i = 0;
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入密码：");
        String password = scanner.next();
        if (isManager==0){
            User user = null;
            try {
                user = getUserByUsername(username);
                if (user==null){
                    System.out.println("用户不存在！");
                }

                if (user==null){
                    System.out.println("用户不存在！");
                }else if (user.getStatus()==0) {
                    System.out.println("用户已锁定！请联系管理员");
                } else if (user.getOnline()==1) {
                    System.out.println("用户已在线，请稍后重试");
                    loginOnlineOperation(isManager);
                } else {
                    while (flag) {
                        i++;
                        if (!user.getPassword().equals(password)){
                            System.out.println("密码错误！");
                            System.out.println("用户"+user.getUsername()+"：还有"+(USERLOGINCOUNT-i)+"次机会");
                            if (i==USERLOGINCOUNT){
                                user.setStatus(0);
                                updateUser(user);
                                user.toString();
                                System.out.println("账户已被锁定，请联系管理员！");
                                System.exit(0);
                            }

                            String ops = userOrAdminLoginFalse(0);
                            if (ops.equals("1") || ops.equals("2")){
                                return;
                            }
                            System.out.println("请重新输入密码：");
                            password = scanner.next();

                        }else {
                            flag = false;
                            isUserLogin = true;
                            USERNAME = user.getUsername();
                        }
                    }
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                if (user!=null){
                    long minutes = Duration.between(user.getLastActionTime(), LocalDateTime.now()).toMinutes();
                    if (minutes >= 5) {
                        setUserOnlineStatus(user.getUsername(),0);
                    }
                }

                if (isUserLogin){
                    try {
                        UserConnection.start(USERNAME);   // ← 唯一入口
                    } catch (Exception e) {
                        System.out.println("无法连接到服务，请稍后再试。");
                        return;
                    }
                    System.out.println("登录成功！");
                    System.out.println("欢迎用户："+USERNAME);
                    setUserOnlineStatus(USERNAME,1);
                    DbUtil.touchUser(user.getId());
                    // 登录成功日志
                    String log = "[上线日志] 用户:" + USERNAME + " 已上线 " + java.time.LocalDateTime.now();
                    sendLogToService(log);
                    userLoginTrue();
                }else {
                    if (i!=USERLOGINCOUNT){
                        String ops = userOrAdminLoginFalse(0);
                        if ("3".equals(ops)){
                            userOrAdminLogin(0);
                        }
                    }
                }
            }
        }else {
            Admin admin = null;
            try {
                admin = getAdminByUsername(username);

                if (admin==null){
                    System.out.println("用户不存在！");
                }else if (admin.getStatus()==0) {
                    System.out.println("用户已锁定！请联系管理员");
                }else if (admin.getOnline()==1) {
                    System.out.println("用户已在线，请稍后重试");
                    loginOnlineOperation(isManager);
                } else {
                    while (flag) {
                        i++;
                        if (!admin.getPassword().equals(password)){
                            System.out.println("密码错误！");
                            System.out.println("用户"+admin.getUsername()+"：还有"+(USERLOGINCOUNT-i)+"次机会");

                            if (i==USERLOGINCOUNT){
                                System.out.println("该账户已被锁定，请五分钟后再试！");
                                System.exit(0);
                            }
                            String ops = userOrAdminLoginFalse(0);
                            if (ops.equals("1") || ops.equals("2")){
                                return;
                            }
                            System.out.println("请重新输入密码：");
                            password = scanner.next();

                        }else {
                            flag = false;
                            isAdminLogin = true;
                            ADMINNAME = admin.getUsername();
                        }
                    }
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                if (admin!=null){
                    long minutes = Duration.between(admin.getLastActionTime(), LocalDateTime.now()).toMinutes();
                    if (minutes >= 5) {
                        setUserOnlineStatus(admin.getUsername(),0);
                    }
                }

                if (isAdminLogin ){
                    try {
                        AdminConnection.start(ADMINNAME);   // ← 唯一入口
                    } catch (Exception e) {
                        System.out.println("无法连接到服务，请稍后再试。");
                        return;
                    }
                    // 建立长连接，保持在线

                    System.out.println("登录成功！");
                    System.out.println("欢迎用户："+ADMINNAME);
                    setAdminOnlineStatus(ADMINNAME,1);
                    DbUtil.touchAdmin(admin.getId());
//                    sendLogToService();
                    String log = "[上线日志] 管理员:" + ADMINNAME + " 已上线 " + java.time.LocalDateTime.now();
                    sendLogToService(log);
                    adminLoginTrue();
                }else {
                    if (i!=USERLOGINCOUNT){
                        String ops = userOrAdminLoginFalse(1);
                        if ("3".equals(ops)){
                            userOrAdminLogin(1);
                        }
                    }
                }
            }
        }
    }
    //用户已在线操作
    public static void loginOnlineOperation(int isManager) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.再试一试  2.退出");
        String ops = scanner.next();
        boolean flag = true;
        while (flag) {
            switch (ops) {
                case "1": {
                    userOrAdminLogin(isManager);
                    flag = false;
                    break;
                }
                case "2": {
                    System.out.println("已退出！");
                    System.exit(0);
                    break;
                }
                default: {
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }


    //用户登录失败操作
    public static String userOrAdminLoginFalse(int isManager) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        String ops = null;
        while (flag) {
            System.out.println("请选择操作功能：");
            System.out.println("1.忘记密码 2.去注册 3.再试一试 4.退出");
            ops = scanner.next();
            switch (ops) {
                case "1": {
                    forgetUserOrAdminPassword(isManager);
                    flag = false;
                    break;

                }
                case "2": {
                    registerUserOrAdmin(isManager);
                    flag = false;
                    break;

                }
                case "3": {
                    flag = false;
                    break;
                }
                case "4": {
                    System.out.println("已退出！");
                    System.exit(0);
                    break;
                }
                default: {
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
        return ops;
    }

    /*=======================================用户注册模块============================================*/
    //注册用户
    public static void registerUserOrAdmin(int isManager) {  //0为用户 1为管理员
        if (isManager==0){
            System.out.println("================================== 用户注册页面 ======================================");
        }else {
            System.out.println("================================== 管理员注册页面 ======================================");
        }
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入姓名：");
        String name = scanner.next();
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入密码：");
        String password = scanner.next();
        try {
            if (isManager==0){
                User user = getUserByUsername(username);
                if (user != null){
                    System.out.println("用户已存在！");
                }else {
                    User user1 = new User();
                    user1.setName(name);
                    user1.setUsername(username);
                    user1.setPassword(password);
                    user1.setMoney(0.0);
                    user1.setStatus(1);
                    user1.setOnline(0);
                    user1.setLastActionTime(LocalDateTime.now());
                    addUser(user1);
                    System.out.println("注册成功！");
                    userRegisterSuccess(isManager);
                }
            }else {
                Admin admin = getAdminByUsername(username);
                if (admin != null){
                    System.out.println("用户已存在！");
                }else {
                    Admin admin1 = new Admin();
                    admin1.setName(name);
                    admin1.setUsername(username);
                    admin1.setPassword(password);
                    admin1.setStatus(1);
                    admin1.setOnline(0);
                    admin1.setLastActionTime(LocalDateTime.now());
                    addAdmin(admin1);
                    System.out.println("注册成功！");
                    userRegisterSuccess(isManager);
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //用户/管理员注册成功或失败选项
    public static void userRegisterSuccess(int isManager) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择操作功能：");
        System.out.println("1.去登录 2.再试一试 2.退出");
        String ops = scanner.next();
        boolean flag = true;
        while (flag) {
            switch (ops) {
                case "1": {
                    userOrAdminLogin(isManager);
                    flag = false;
                    break;
                }
                case "2": {
                    flag = false;
                    break;
                }
                case "3": {
                    System.out.println("已退出！");
                    System.exit(0);
                    break;
                }
                default: {
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }

    /*======================================用户忘记密码模块====================================*/
    //忘记用户/管理员密码
    public static void forgetUserOrAdminPassword(int isManager) throws SQLException {
        if (isManager==0){
            System.out.println("================================== 用户忘记密码页面 ======================================");
        }else {
            System.out.println("================================== 管理员忘记密码页面 ======================================");
        }
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入新密码：");
        String newPw1 = scanner.next();
        System.out.println("请输入确认密码：");
        String newPw2 = scanner.next();
        if (isManager==0){
            User user = getUserByUsername(username);
            if (user == null){
                System.out.println("用户不存在！");
                userOrAdminForgetUserPWFalse(isManager);
            }else {
                if (!newPw1.equals(newPw2)) {
                    System.out.println("密码不一致！");
                    userOrAdminForgetUserPWFalse(isManager);
                } else {
                    try {
                        user.setPassword(newPw1);
                        updateUser(user);
                        System.out.println("修改成功！");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }else {
            Admin admin = getAdminByUsername(username);
            if (admin == null){
                System.out.println("用户不存在！");
                userOrAdminForgetUserPWFalse(isManager);
            }else {
                if (!newPw1.equals(newPw2)) {
                    System.out.println("密码不一致！");
                    userOrAdminForgetUserPWFalse(isManager);
                } else {
                    try {
                        admin.setPassword(newPw1);
                        updateAdmin(admin);
                        System.out.println("修改成功！");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

    }

    //忘记密码输入错误选择
    public static void userOrAdminForgetUserPWFalse(int isManager) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.println("请选择操作功能：");
            System.out.println("1.去登录 2.去注册 3.再试一试 4.退出");
            String ops = scanner.next();
            switch (ops) {
                case "1": {
                    userOrAdminLogin(isManager);
                    flag = false;
                    break;

                }
                case "2": {
                    registerUserOrAdmin(isManager);
                    flag = false;
                    break;
                }
                case "3": {
                    flag = false;
                    forgetUserOrAdminPassword(isManager);
                    break;
                }
                case "4": {
                    System.out.println("已退出！");
                    System.exit(0);
                    break;
                }
                default: {
                    System.out.println("操作错误！请重新输入");
                    break;
                }
            }
        }
    }
}
